package com.thinkit.directive.config;

import com.thinkit.utils.properties.ThinkItProperties;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName: BeanConfig
 * @Author: LG
 * @Date: 2019/5/16 13:29
 * @Version: 1.0
 **/
@Slf4j
@Configuration
public class FreeMarkConfig {

    @Bean
    public freemarker.template.Configuration configuration(ThinkItProperties thinkItProperties) throws IOException, TemplateException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_28);
        cfg.setDirectoryForTemplateLoading(initFile(thinkItProperties));
        cfg.setObjectWrapper(new DefaultObjectWrapper(freemarker.template.Configuration.VERSION_2_3_28));
        cfg.setTemplateExceptionHandler(templateExceptionHandler());
        cfg.setWrapUncheckedExceptions(true); // 将模板处理期间抛出的未经检查的异常包装到 TemplateException-s 中：
        cfg.setClassicCompatible(true);// 空值不报错
        cfg.setDefaultEncoding("UTF-8");
        cfg.setSetting("number_format","0.##");
        return cfg;
    }

    @Bean
    TemplateExceptionHandler templateExceptionHandler(){
        return new FreemarkerExceptionHandler();
    }

    private File initFile(ThinkItProperties thinkItProperties){
        File file = new File(thinkItProperties.getTemplate());
        if(!file.exists()){
            file.mkdirs();
        }
        return file;
    }

}
